﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace DIProject.Sales
{	public partial class CashReceipt : CashOperation
	{	public	DIProject.DataSets.Sales.NewCashRegisterDocRow NewDoc{get{return newDoc;}}
		private	DIProject.DataSets.Sales.NewCashRegisterDocRow newDoc = null;

		public override decimal Sum
		{	get
			{	object s = sales.CashRegisterLines.Compute(string.Format("sum({0})", retailSumDataGridViewTextBoxColumn.DataPropertyName), null);
				return s is decimal? (decimal)s: 0m;
			}
		}
//-------------------------------------------------------------------------------------------------
		public CashReceipt() : this(null)	// Для дизайнера
		{

		}

		public CashReceipt(ToolStripMenuItem menuItem) : base(menuItem)
		{	InitializeComponent();
		}
//-------------------------------------------------------------------------------------------------
    protected override void SetCaption()
    {
        Text = string.Format
        (TextFormat
        , CashRegisterName
        , /*newDoc == null || newDoc.RowState == DataRowState.Detached
            ? string.Empty// Properties.Resources.strUndefined
            : newDoc.DocNumber*/
        string.Empty
        , Sum.ToString("N2")
        );
        FirstForm ff = this.MdiParent as FirstForm;
        if (ff != null)
        {
            ff.lblMessage.Text = this.Text;
        }
    }

		private void CashReceipt_Load(object sender, EventArgs e)
		{	qnttyDataGridViewTextBoxColumn1.HeaderText = "Остаток";
			EnableControls(false);
			sales.CashRegisterLines.CashRegisterLinesRowDeleted += new DIProject.DataSets.Sales.CashRegisterLinesRowChangeEventHandler(CashRegisterLinesRowDeleted);
            Util.CashRecorder.OpenCheck(DIProject.Util.CheckType.Sale);
            Util.CashRecorder.CancelCheck();
		}

		private void CashReceipt_FormClosed(object sender, FormClosedEventArgs e)
		{	
            Util.CashDisplay.Clear();	// Очистка кассового дисплея
            FirstForm ff = this.MdiParent as FirstForm;
            if (ff != null)
            {
                ff.lblMessage.Text = string.Empty;
            }
		}
//-------------------------------------------------------------------------------------------------
		private void EnableControls(bool enable)
		{	modified = enable;
			toolStripButtonCreate.	Enabled = !enable;
            toolStripButtonRefresh.Enabled = enable;// newDoc != null && newDoc.RowState != DataRowState.Detached;
			toolStripButtonClose.	Enabled = enable;
			toolStripButtonCancel.	Enabled = enable;
			textBoxQntty.			Enabled = enable;
            ///кнопка создания отказа
           // btnRefusal.Enabled = !enable;
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
// Операции с документом
		protected override void RefreshDoc()
		{
     /*   if (newDoc == null)
            return;
            //cashRegisterLines.BeginEdit(true);
            cashRegisterLinesTableAdapter.Fill(sales.CashRegisterLines, newDoc.Id);
            //cashRegisterLines.EndEdit();*/
        sales.CashRegisterLines.Clear();
		}


    private decimal GetSumm
    {
        get
        {
            if (cashRegisterLines.Rows.Count < 1)
            {
                return 0;
            }
            decimal result = 0;
            foreach (DataGridViewRow r in cashRegisterLines.Rows)
            {
                DataRowView drv = r.DataBoundItem as DataRowView;
                DIProject.DataSets.Sales.CashRegisterLinesRow csr = drv.Row as DIProject.DataSets.Sales.CashRegisterLinesRow;
                result += csr.RetailPrice * csr.Qntty;
            }
            return result;
        }
    }
		decimal paid, change;
		protected override void CloseNewDoc()
		{
            try
			{
                // Запрос суммы оплаченной клиентом
                CashPaid cashPaid = new CashPaid();
                cashPaid.numericUpDownPaid.Value = paid = Sum;
                bool flag = true;
                while (flag)
                {
                    DialogResult dilRes = cashPaid.ShowDialog(this);
                    if (dilRes == DialogResult.Cancel)
                        {
                        RefreshDoc();
                        return;
                        }
                    if (dilRes == DialogResult.OK)
                        paid = cashPaid.numericUpDownPaid.Value;			// оплаченная сумма
                    if ((paid < this.GetSumm)&&(cashPaid.Payment == DIProject.Util.TypePayment.CASH))
                    {
                        MessageBox.Show("Введенная сумма меньше суммы чека! Введите правильную сумму!", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        flag = false;
                    }
                }
                byte disc = cashPaid.Discount;
                Util.TypePayment payment = cashPaid.Payment;
                // Вывод итога чека на кассовом дисплее
                DIProject.Data.Cash cash = null;
                bool rs = RunSale(ref cash, disc, payment);
                //неудалось печатать чек, выходим
                if (!rs)
                    return;
				Util.CashDisplay.Line1 = string.Format("Итого: {0,13}", Sum.ToString("N2", Util.CashDisplay.NumberFormat));
				Util.CashDisplay.Line2 = null;

			
			//	Закрытие чека на фискальном регистраторе
                try
                {
                    ///если скидка больше 0 и оплата по карте
                    if ((disc > 0)||(payment == DIProject.Util.TypePayment.PAYMENTCARD))
                        change = Util.CashRecorder.CloseCheck1(newSum1, payment);
                    else
                        change = Util.CashRecorder.CloseCheck1(paid, payment);	// закрытие чека - возвращает сдачу
                    Util.DILogInFile.LogCachCloseDoc(cash.MD, cash.CashDocId);
                    Util.CashRecorder.GetECRStatus();
                    if (Util.CashRecorder.ResultCode != 0)
                    {
                        throw new Util.DIException("Невозможно пробить чек\n" + Util.CashRecorder.ResultDescription);
                    }
                }
                catch (Exception ee)
                {
                    if (cash != null)
                    {
                        cash.Rollback();
                        Util.CashRecorder.CancelCheck();
                        Util.DILogInFile.LogCashCancelDoc(cash.MD, cash.CashDocId);
                    }
                }

				backgroundWorkerShowInfo.RunWorkerAsync();

			// Вывод сдачи по чека на кассовом дисплее
				if(change > decimal.Zero)
					Util.CashDisplay.Line2 = string.Format("Сдача: {0,13}", change.ToString("N2", Util.CashDisplay.NumberFormat));
              //  newDoc = null;

				EnableControls(false);
                //автоматически новый чек
                if (this.checkAutomate.Checked)
                {
                    this.toolStripButtonCreate_Click(this.toolStripButtonCreate, EventArgs.Empty);
                }
                cash = null;
               // RefreshDoc();
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		protected override void CancelNewDoc()
		{	try
			{	if(newDoc != null)
				{	newDoc.Delete();
					newCashRegisterDocTableAdapter.Update(sales.NewCashRegisterDoc);
					sales.CashRegisterLines.Rows.Clear();				
                    newDoc = null;                    //RefreshDoc();                
				}
                EnableControls(false);
                //	Аннулирование чека на фискальном регистраторе
                Util.CashRecorder.CancelCheck();	// аннулирование
                Util.CashRecorder.CutCheck(DIProject.Util.CheckCutMode.Partial);
			}
			catch(SqlException eq)
			{	
                MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	
                MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
    string oldGood = string.Empty;
//-------------------------------------------------------------------------------------------------
// Операции со строками документа
		protected override bool LineInsert()
            {
            
            int qntty;
			bool ok = false;
			if(/*newDoc != null
			&& */SearchedGoodsRow != null
			&& (qntty = int.Parse(textBoxQntty.Text)) > 0
			&& qntty <= SearchedGoodsRow.Qntty)
			{	DIProject.DataSets.Sales.CashRegisterLinesRow newLine = sales.CashRegisterLines.NewCashRegisterLinesRow();
				try
                {
                    newLine.DocId = Int32.MinValue;// newDoc.Id;
					newLine.PartyId				= SearchedGoodsRow.PartyId;
					newLine.Name				= SearchedGoodsRow.Name;
					newLine.ManufacturerName	= SearchedGoodsRow.ManufacturerName;
					newLine.Qntty				= qntty;
					newLine.RetailPrice			= SearchedGoodsRow.RetailPrice;
					newLine.RetailSum			= qntty*SearchedGoodsRow.RetailPrice;
					newLine.Note				= null;
					newLine.MD					= DateTime.Now;
					newLine.MW					= FirstForm.Login;
					sales.CashRegisterLines.AddCashRegisterLinesRow(newLine);
					//cashRegisterLinesTableAdapter.Update(newLine);

					SearchedGoodsRow.Qntty -= qntty;
					SetCaption();
				// Печать строки чека на фискальном регистраторе
                    string tmp = newLine.Name;
                    if (tmp.Length > 33)
                    {
                        tmp = tmp.Substring(0, 33);
                    }
					//Util.CashRecorder.Sale(tmp, newLine.Qntty, newLine.RetailPrice);
				// Вывод строки чека на кассовом дисплее
					Util.CashDisplay.Line1 = newLine.Name;
					Util.CashDisplay.Line2 = string.Format
						(	"{0,7}x{1,3}={2,8}"
						,	newLine.RetailPrice.ToString("N2", Util.CashDisplay.NumberFormat)
						,	newLine.Qntty.ToString("N0", Util.CashDisplay.NumberFormat)
						,	newLine.RetailSum.ToString("N2", Util.CashDisplay.NumberFormat)
						);
                    textBoxQntty.Text = "1";
					ok = true;
				}
				catch(SqlException eq)
				{	newLine.RejectChanges();
					MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	newLine.RejectChanges();
					MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
			else
				Console.Beep();
			return ok;
		}
		protected override bool LineUpdate(int rowIndex)
		{	DIProject.DataSets.Sales.CashRegisterLinesRow changedLine = sales.CashRegisterLines[rowIndex];
			try
                {
                Int32 tmp;
                int		//oldQntty = (int)changedLine[sales.CashRegisterLines.QnttyColumn]//, DataRowVersion.Original]
						newQntty = changedLine.Qntty;
            Int32 old = Data.Party.GetPartyCount(changedLine.PartyId);
            tmp = newQntty;
            if (newQntty > old)
                {
                tmp = old;
                changedLine.Qntty = old;
                }
            if (newQntty < 0)
                {
                tmp = 0;
                changedLine.Qntty = 0;
                }
				//changedLine.BeginEdit();
				changedLine.RetailSum = changedLine.Qntty*changedLine.RetailPrice;
                
				//changedLine.EndEdit();
				//cashRegisterLinesTableAdapter.Update(changedLine);
			// Сторно старого значения, печать нового значения на фискальном регистраторе
				/*if(newQntty > oldQntty)
					Util.CashRecorder.Sale(changedLine.Name, newQntty - oldQntty, changedLine.RetailPrice);
				else if(newQntty < oldQntty)
					Util.CashRecorder.Storno(changedLine.Name, oldQntty - newQntty, changedLine.RetailPrice);*/

				SetCaption();

				return true;
			}
			catch(SqlException eq)
			{	changedLine.RejectChanges();
				MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	changedLine.RejectChanges();
				MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			return false;
		}

		private void CashRegisterLinesRowDeleted(object sender, DIProject.DataSets.Sales.CashRegisterLinesRowChangeEvent e)
		{	try
			{	//string	name	= (string)	e.Row[sales.CashRegisterLines.NameColumn,			DataRowVersion.Original];
				//int		qntty	= (int)		e.Row[sales.CashRegisterLines.QnttyColumn,			DataRowVersion.Original];
				//decimal	price	= (decimal)	e.Row[sales.CashRegisterLines.RetailPriceColumn,	DataRowVersion.Original];
				//cashRegisterLinesTableAdapter.Update(e.Row);
			// Сторно строки на фискальном регистраторе
			//	Util.CashRecorder.Storno(name, qntty, price);

				SetCaption();
			}
			catch(SqlException eq)
			{	e.Row.RejectChanges();
				MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	e.Row.RejectChanges();
				MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void backgroundWorkerShowInfo_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{	CashPayInfo payInfo = new CashPayInfo();
        payInfo.textBoxSum.Text = this.newSum1.ToString("N2");// Sum.ToString("N2");
			payInfo.textBoxPaid.	Text = paid.ToString("N2");
			payInfo.textBoxChange.	Text = change.ToString("N2");
			payInfo.ShowDialog(this);
		}

    private void textBoxBarcode_TextChanged(object sender, EventArgs e)
    {

    }

    private void textBoxName_TextChanged(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// Новый отказ
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {        
        string str = textBoxName.Text;
        if (string.IsNullOrEmpty(str))
            return;
        DialogResult dr = MessageBox.Show("Сохранить отказ для '" + str + "'?", "Сохранение отказа", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        if (dr == DialogResult.Yes)
        {
            DataSets.UtilTableAdapters.UtilQueries goodsIdAdapter = new DIProject.DataSets.UtilTableAdapters.UtilQueries();
            object o = goodsIdAdapter.GoodsIdFromName(str);
            if (Convert.IsDBNull(o))
                return;
            Int32 goodsId = Convert.ToInt32(o);
            Int32 count = Convert.ToInt32(numericUpDown1.Value);
            Data.Refusals.AddRefusal(goodsId, count, string.Empty);
        }
    }

    private void textBoxName_DoubleClick(object sender, EventArgs e)
    {
        textBoxName.SelectAll();
    }
    public override void GetChek()
        {
       // RunSale();
        }
    private decimal newSum = 0;
    private decimal newSum1 = 0;
    private bool RunSale(ref DIProject.Data.Cash cashOut, byte discount, Util.TypePayment payment)
    {
        newSum = 0;
        newSum1 = 0;
        Util.CashDisplay.Clear();
        //создаем объект для работы с БД
        DIProject.Data.Cash cash = null;
        string cString = DIProject.Properties.Settings.Default.DIAptekaConnectionString;
        cash = new DIProject.Data.Cash(cString);
        cashOut = cash;
        bool pm = false;
        if (payment == DIProject.Util.TypePayment.CASH)
            pm = false;
        if (payment == DIProject.Util.TypePayment.PAYMENTCARD)
            pm = true;
        if (cashRegisterLines.Rows.Count > 0)
        {

            #region печатаем чек и вносим в БД
            try
            {
                #region подготовка
                Int32 nextDocNumber;// = Util.CashRecorder.NextDocNumber;                    
                //смотрим что с регистратором
                if (Util.CashRecorder.ResultCode != 0)
                {
                    string eString = "Нельзя пробить чек. Ошибка фескального регистратора\n" +
                        Util.CashRecorder.ResultDescription;
                    MessageBox.Show(eString, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                Util.CashRecorder.OpenCheck(DIProject.Util.CheckType.Sale);
                Util.CashRecorder.GetECRStatus();
                nextDocNumber = Util.CashRecorder.NextDocNumber;
                cash.CashDocId = nextDocNumber;
                Util.DILogInFile.LogCashCreateDoc(DateTime.Now, nextDocNumber);
                Int32 docId = cash.CreateNewDoc2
                (
                Util.CashRecorder.Time,
                nextDocNumber,
                this.CashRegisterShiftId,
                null,
                1,
                pm,
                    //false,                
                null,
                DateTime.Now,
                FirstForm.Login
                );
                Util.DILogInFile.LogDBCreateDoc(cash.MD, nextDocNumber);
                #endregion
                DataSets.SalesTableAdapters.QueriesTableAdapter GoodsFromPartyAdapter = new DIProject.DataSets.SalesTableAdapters.QueriesTableAdapter();
                #region foreach заносим данные в БД!
                foreach (DataGridViewRow ro in cashRegisterLines.Rows)
                {
                    DIProject.DataSets.Sales.CashRegisterLinesRow newLine = (ro.DataBoundItem as DataRowView).Row as DIProject.DataSets.Sales.CashRegisterLinesRow;
                    //проверяем реальные остатки в БД, если меньше требуемого, продаем только остатки
                    Int32 old = Data.Party.GetPartyCount(newLine.PartyId);
                    if (old < newLine.Qntty)
                    {
                        newLine.Qntty = old;
                    }
                    decimal rSum = newLine.RetailSum;
                    newSum1 += rSum;
                    if (discount > 0)
                    {
                        rSum = rSum - rSum * discount / 100;
                        rSum = decimal.Round(rSum, 2, MidpointRounding.AwayFromZero);
                    }
                    newSum += rSum;
                    if (newLine.Qntty > 0)
                    {
                        Int32 chId = cash.InsertNewLine2
                            (docId,
                            newLine.PartyId,
                            newLine.Qntty,
                            rSum,
                            //newLine.RetailSum,
                            discount,
                            string.Empty,
                            DateTime.Now,
                            FirstForm.Login
                            );
                        Int32 goodId = (Int32)GoodsFromPartyAdapter.GoodsFromParty(newLine.PartyId);
                        Util.DILogInFile.LogDBSale(cash.MD, nextDocNumber, newLine.PartyId, goodId, newLine.Qntty, rSum);
                    }
                }
                if(discount>0)
                {
                    newSum1 = newSum1 - newSum1 * discount / 100;
                    newSum1 = decimal.Round(newSum1, 2, MidpointRounding.AwayFromZero);
                }
                #endregion
                #region другой foreach
                Util.CashRecorder.DiscountOnCheck = discount;
                foreach (DataGridViewRow ro in cashRegisterLines.Rows)
                {
                    DIProject.DataSets.Sales.CashRegisterLinesRow newLine = (ro.DataBoundItem as DataRowView).Row as DIProject.DataSets.Sales.CashRegisterLinesRow;
                    string tmp = newLine.Name;
                    if (tmp.Length > 33)
                    {
                        tmp = tmp.Substring(0, 33);
                    }
                    #region if
                    if (newLine.Qntty > 0)
                    {
                        Util.CashRecorder.GetECRStatus();
                        if (Util.CashRecorder.ResultCode != 0)
                        {
                            while (Util.CashRecorder.WaitForPrinting() != 0)
                            {
                                string str = Util.CashRecorder.ResultDescription;
                                DialogResult dRes = MessageBox.Show
                                    (
                                    "Фескальный регистратор в состоянии\n" + str +
                                    "Что бы подождать нажмите \"Ok\", чтобы прервать печать \"Отмена\""
                                    ,
                                    "Предупреждение!",
                                    MessageBoxButtons.OKCancel,
                                    MessageBoxIcon.Warning
                                    );
                                if (dRes == DialogResult.Cancel)
                                {
                                    Util.CashRecorder.CancelCheck();	// аннулирование
                                    Util.DILogInFile.LogCashCancelDoc(cash.MD, cash.CashDocId);
                                    Util.CashRecorder.CutCheck(DIProject.Util.CheckCutMode.Partial);
                                    cash.Rollback();
                                    MessageBox.Show("Чек аннулирован!", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    return false;
                                }
                            }
                        }
                        Util.CashRecorder.Sale(tmp, newLine.Qntty, newLine.RetailPrice);
                        Int32 goodId = (Int32)GoodsFromPartyAdapter.GoodsFromParty(newLine.PartyId);
                        Util.DILogInFile.LogCashSale(cash.MD, nextDocNumber, newLine.PartyId, goodId, newLine.Qntty, newLine.RetailSum);
                    }
                    #endregion
                }
                #endregion
                return true;
            }
            #endregion
            #region ошибка
            catch (Exception ee)
            {
                if (cash != null)
                {
                    cash.Rollback();
                }
                MessageBox.Show
                    (
                    "Невозможно пробить чек!\n" + ee.Message,
                    "Ошибка",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );
                Util.CashRecorder.CancelCheck();
                Util.DILogInFile.LogCashCancelDoc(cash.MD, cash.CashDocId);
                return false;
            }
            #endregion
        }
        return true;
    }
    protected override void CreateNewDoc()
    {
        try
        {
            /*Int32 nextDocNumber = Util.CashRecorder.NextDocNumber;
            newCashRegisterDocTableAdapter.Fill
                (sales.NewCashRegisterDoc
                , Util.CashRecorder.Time	// DocDate
                , nextDocNumber
                , CashRegisterShiftId		// CashRegisterShiftId
                , null					// DepartmentUserId
                , null					// Note
                , DateTime.Now			// MD
                , FirstForm.Login			// MW
                );
            newDoc = sales.NewCashRegisterDoc[0];*/
            //newDoc.DocNumber= Util.CashRecorder.NextDocNumber.ToString();
            //newCashRegisterDocTableAdapter.Update(newDoc);
            //cashRegisterLinesTableAdapter.Fill(sales.CashRegisterLines, newDoc.Id);
            // Создание чека на фискальном регистраторе
            /*Util.CashRecorder.OpenCheck
            (	DIProject.Util.CheckType.Sale											// продажа
            ,	BitConverter.ToUInt32(BitConverter.GetBytes(newDoc.Id), 0).ToString()	// штрих-код на чек
            );*/
            // Очистка кассового дисплея
            Util.CashDisplay.Clear();
            RefreshDoc();
            EnableControls(true);
        }
        catch (SqlException eq)
        {
            MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    private void CashReceipt_Deactivate(object sender, EventArgs e)
    {
        FirstForm ff = this.MdiParent as FirstForm;
        if (ff != null)
        {
            ff.lblMessage.Text = string.Empty;
        }
    }
//-------------------------------------------------------------------------------------------------
    /// <summary>
    /// Делим вроде как товар
    /// </summary>
    /// <param name="row"></param>
    protected override void DivGood(DIProject.DataSets.Sales.GoodsSearchRow row)
    {
    DialogResult dr = MessageBox.Show("Разукомплектовать товар " + row.Name + "?", "Разукомплектование товара", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
    if (dr != DialogResult.OK)
        return;
        DIProject.Stock.CashDisgather cd = new DIProject.Stock.CashDisgather(row);
        cd.ShowDialog();
        if (cd != null)
            cd.Close();
    }
    //по нажатию Enter добавляем с введенным количеством в чек
    private void textBoxQntty_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            LineInsert();
        }
    }
	}
}